<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle 
        v-if="hasPermission('msgPush:SaveMsgGroup') || hasPermission('msgPush:DeleteMsgNotice') || hasPermission('msgPush:SaveMsgNotice')"
      >
        <a-button preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd"
          style="margin-right: 5px" v-auth="'msgPush:SaveMsgNotice'"
        >
          新增
        </a-button>

        <a-button 
          type="primary" 
          preIcon="ant-design:edit-outlined" 
          @click="handleOpenGroup"
          v-auth="'msg:msgGroup:save'"
        >
          功能组
        </a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0 && hasPermission('msg:msgNotice:delete')">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <template #channelList="{ record }"> 
        <template v-for="(item, index) in record.channelList" :key="index">
          <div :class="`${prefixCls}-channel`">
            <div :class="`${prefixCls}-channel-item`" @click="handleMsgSetting(record, item)">
              <Icon v-if="item.status === '1'" icon="simple-line-icons:check" :class="`${prefixCls}-channel-icon`"></Icon>
              <Icon v-else icon="simple-line-icons:check"></Icon>
              <span>{{ item.name }}</span>
            </div>
          </div>
        </template>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
    </BasicTable>
    <MsgNoticeForm @register="registerMsgNoticeForm" @success="reload" showFooter/>
    <MsgNoticeDetail @register="registerMsgNoticeDetail"/>
    <ConfigChannel @register="registerConfigChannel" @success="reload"/>
    <MyDataGroupList @register="registerGroupDrawer" @success="reload" :bizType="DataGroupBizType.MSG_PUSH_TASK"/>
    <MsgReceiverList @register="registerMsgReceiverList"/>
  </div>
</template>
<script lang="ts" name="msg-notice" setup>
import { ref } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import MsgNoticeDetail from './components/MsgNoticeDetail.vue';
import { CheckboxGroup } from 'ant-design-vue'
import { useDrawer } from '/@/components/Drawer';
import { 
  pageNotice, deleteNotice, batchDeleteNotice,
  saveOrUpdateGroup, deleteGroup, batchDeleteGroup,
  updateNoticeStatus
} from './api';
import { columns, searchFormSchema } from './data';
import MsgNoticeForm from './components/MsgNoticeForm.vue';
import ConfigChannel from './components/ConfigChannel.vue';
import MsgReceiverList from './components/MsgReceiverList.vue';
import { ReceiverType } from '../receiver/receiver.data';

import { useMessage } from "/@/hooks/web/useMessage";
import { useListPage } from '/@/hooks/system/useListPage'
import { Icon } from '/@/components/Icon'
import { useUserStore } from '/@/store/modules/user';
import { useModal } from '/@/components/Modal';
import { usePermission } from '/@/hooks/web/usePermission';
import { useDesign } from '/@/hooks/web/useDesign';
import { isManageOrPlatform } from '/@/utils/tenant';
import { MyDataGroupList, DataGroupBizType } from "/@/components/BizDataGroup/index"

const [registerMsgReceiverList, { openDrawer: openMsgReceiverList }] = useDrawer()
const [registerGroupDrawer, { openDrawer: openGroupDrawer }] = useDrawer();
const [registerConfigChannel, { openModal: openConfigChannel }] = useModal();
const { prefixCls } = useDesign('msg-notice');
const { hasPermission } = usePermission();
const userStore = useUserStore()
const [registerMsgNoticeForm, { openDrawer: openMsgNoticeForm }] = useDrawer()
const [registerMsgNoticeDetail, { openDrawer: openMsgNoticeDetail }] = useDrawer()
const { createMessage } = useMessage();

const { tableContext } = useListPage({
  designScope: 'msg-notice',
  tableProps: {
    title: '消息模板列表',
    api: pageNotice,
    bordered: false,
    rowSelectionTipType: '',
    showTableSetting: false,
    actionColumn: {
      width: 220,
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
    columns: columns,
    formConfig: {
      schemas: searchFormSchema,
      fieldMapToTime: [['fieldTime', ['beginDate', 'endDate'], 'YYYY-MM-DD HH:mm:ss']]
    }
  }
})
const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

function getTableAction(record) {
  return [
    {
      label: '删除',
      color: 'error',
      auth: 'msgPush:DeleteMsgNotice',
      ifShow: () => isManageOrPlatform(userStore),
      popConfirm: {
        title: `是否确认删除 ${record.name}`,
        confirm: handleDelete.bind(null, record),
      },
    },
    {
      label: '详情',
      onClick: handleMsgNoticeDetail.bind(null, record),
    },
    {
      label: '禁用',
      ifShow: record.status,
      color: 'warning',
      onClick:  handleUpdateStatus.bind(null, record, false)
    }, 
    {
      label: '启用',
      ifShow: !record.status,
      color: 'success',
      onClick:  handleUpdateStatus.bind(null, record, true)
    }
  ]
}

const handleMsgNoticeDetail = (record) => {
  openMsgNoticeDetail(true, { record });
}

const handleMsgSetting = (record, selectedChannel) => {
  console.log('handleMsgSetting', record, selectedChannel)
  openConfigChannel(true, {  record, selectedChannel, showEdit: false });
}


 function getDropDownAction(record): ActionItem[] {
  return [
    {
      label: '配置渠道',
      ifShow: (e) => isManageOrPlatform(userStore),
      onClick: handleOpenConfigChannel.bind(null, record),
    },
    {
      label: '编辑',
      auth: 'msgPush:UpdateMsgNotice',
      ifShow: () => isManageOrPlatform(userStore),
      onClick: handleEdit.bind(null, record),
    },
    {
      label: '接收人',
      ifShow: (e) => record.receiverType === ReceiverType.ADMIN, // 2为管理员
      onClick: handleOpenMsgReceiverList.bind(null, record),
    }
    
  ]
}


function handleAdd() {
  openMsgNoticeForm(true, {
    isUpdate: false,
  });
}

function handleEdit(record) {
  openMsgNoticeForm(true, {
    record,
    isUpdate: true,
  });
}

async function handleDelete(record) {
  await deleteNotice({ id: record.id }, reload);
}

async function batchHandleDelete() {
  await batchDeleteNotice({ ids: selectedRowKeys.value }, reload);
}

function handleOpenConfigChannel(record, showEdit = true) {
  if (!record.channelList || record.channelList.length === 0) {
    createMessage.warn('无可用渠道, 请先编辑消息选择可用渠道')
    return
  }
  openConfigChannel(true, {  record, showEdit });
}

function handleOpenGroup() {
  openGroupDrawer(true, {
    title: '消息功能组',
    width: 800,
    deleteApi: deleteGroup,
    batchDeleteApi: batchDeleteGroup,
    saveOrUpdateApi: saveOrUpdateGroup
  })
}

/**
 * 打开消息接收人列表
 */
 function handleOpenMsgReceiverList(record) {
  openMsgReceiverList(true, { record });
}

async function handleUpdateStatus(record, status) {
  await updateNoticeStatus({ id: record.id, status })
  createMessage.success(status ? '启用成功' : '禁用成功')
  reload()
}

</script>


<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-msg-notice';

  .@{prefix-cls} {
    
    &-channel {
      transition: all 0.2s ease;
      div {
        float: left;
        margin-left: 5px;
        cursor: pointer;
        text-align: center;
        vertical-align: middle;

        span {
          text-align: center;
          vertical-align: middle;
          margin-left: 2px;
        }
      }

      div:hover{
        color: @hover-color !important;
        span {
          color: @hover-color !important;
        }
      }

      &-icon {
        color: @hover-color;
      }
    }
  }
</style>
